import datetime
import json

from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
from django.views import View
from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from booktest.models import BookInfo
from rest_framework.viewsets import ModelViewSet
from .serializers import BookInfoSerializer

# class BooksAPIView(View):
#     """查询所有图书
#     路由：GET /books"""
#     def get(self, request):
#         queryset = BookInfo.objects.all()
#
#         book_list = []
#         for book in queryset:
#             book_list.append({
#                 'id':book.id,
#                 'btitle':book.btitle,
#                 'bpub_date': book.bpub_date,
#                 'bread': book.bread,
#                 'bcomment': book.bcomment,
#                 'image':book.image.url if book.image else None
#             })
#         return JsonResponse(book_list, safe=False)
#
#     def post(self, request):
#         """新增图书
#         路由： POST /books"""
#         # 接受前段传过来的数据， 是字节类型，需要转换类型
#         raw_data = request.body
#         str_data = raw_data.decode()
#         # 将字符串类型转为字典
#         dict_data = json.loads(str_data)
#
#         book = BookInfo.objects.create(
#             btitle = dict_data.get('btitle'),
#             bpub_date = dict_data.get('bpub_date')
#         )
#
#         return JsonResponse({
#             'id': book.id,
#             'btitle': book.btitle,
#             'bpub_date': book.bpub_date,
#             'bread': book.bread,
#             'bcomment': book.bcomment,
#             'image': book.image.url if book.image else None
#         }, status=201)
#
#
# class BookAPIView(View):
#
#     def get(self,request, id):
#         """获取一本书"""
#         try:
#             book = BookInfo.objects.get(id=id)
#         except Exception as e:
#             raise e
#
#         return JsonResponse({
#             'id': book.id,
#             'btitle': book.btitle,
#             'bpub_date': book.bpub_date,
#             'bread': book.bread,
#             'bcomment': book.bcomment,
#             'image': book.image.url if book.image else None
#         })
#
#     def put(self, request, id):
#         try:
#             book = BookInfo.objects.get(id=id)
#         except Exception as e:
#             raise e
#
#         # 获取前端来的数据
#         raw_data = request.body
#         str_data = raw_data.decode()
#         # 将字符串类型转为字典
#         dict_data = json.loads(str_data)
#
#         # 修改数据
#         book.btitle = dict_data['btitle']
#         book.bpub_date = dict_data['bpub_date']
#         book.save()
#
#         return JsonResponse({
#             'id': book.id,
#             'btitle': book.btitle,
#             'bpub_date': book.bpub_date,
#             'bread': book.bread,
#             'bcomment': book.bcomment,
#             'image': book.image.url if book.image else None
#         })
#
#     def delete(self, request, id):
#         """"""
#         try:
#             book = BookInfo.objects.get(id=id)
#         except Exception as e:
#             raise e
#
#         book.delete()

class BookInfoViewset(ModelViewSet):
    # 获取当前要操作的数据
    #queryset 当前视图集要进行操作的查询集
    queryset = BookInfo.objects.all()
    # 数据格式转化或者数据校验
    # 指明进行序列化或反序列化的序列化器
    serializer_class = BookInfoSerializer
    filter_backends = [OrderingFilter]
    ordering_fields = ('id', 'bread', 'bpub_date')
    # filter_fields = ('btitle', 'bread')  #可以进行过滤

    @action(methods=['get'], detail=False)
    def latest(self,request):
        """返回最新的一本图书信息"""
        book = BookInfo.objects.latest('id')
        ser = BookInfoSerializer(book)
        return Response(ser.data)


# class BookDetailView(GenericAPIView, ListModelMixin, CreateModelMixin, RetrieveModelMixin,UpdateModelMixin, DestroyModelMixin):
class BookDetailView(ListCreateAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get_all_books(self,request):
        return self.list(request)

    def create_book(self, request):
        return self.create(request)


class BookDetailView2(RetrieveUpdateDestroyAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get_one_book(self, request, pk):
        return self.retrieve(request)

    def update_one_book(self,request, pk):
        return self.update(request)

    def delete_one_book(self, request, pk):
        return self.destroy(request)
    # def get(self, request, pk):
    #     # 获取查询集对象
    #     book = self.get_object()
    #     ser = self.get_serializer(book)
    #     return Response(ser.data)
    # def get(self, request):
    #     return self.list(request)
    #
    # def post(self, request):
    #     return self.create(request)

    # def get_book(self, request, pk):
    #     return self.retrieve(request)
    # def get(self, request, pk):
    #     return self.update(request)
    # def delete(self,request, pk):
    #     return self.destroy(request)